package utils;

import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class SSHUtils {

public static boolean RegisterUser(String user, String pass)
{
	try{
	 JSch jsch=new JSch();
	 Session session=jsch.getSession("root", "localhost", 22);
     
	 UserInfo ui = new MyUserInfo();
	 session.setUserInfo(ui);
     //session.connect();
     session.connect(30000);   // making a connection with timeout.
     
     PipedInputStream in = new PipedInputStream();
     PipedOutputStream out = new PipedOutputStream(in);
     
     Channel channel=session.openChannel("shell");

     channel.setInputStream(in);
     channel.setOutputStream(null);
     channel.connect(3*1000);
     String u = "useradd -m "+user+"\n";
     out.write(u.getBytes());
     Thread.sleep(1000);
     u = "passwd "+user+"\n";
     out.write(u.getBytes());
     Thread.sleep(1000);
     u = pass+"\n";
     out.write(u.getBytes());
     Thread.sleep(1000);
     out.write(u.getBytes());
     Thread.sleep(1000);
     u = "rm /home/"+user+"/examples.desktop\n";
     out.write(u.getBytes());
    /* u = "chmod 700 /home/"+user;
     out.write(u.getBytes());*/
     return true;
   }
   catch(Exception e){
     e.printStackTrace();
     return false;
   }
}

public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
	public String getPassword() {
		return passwd;
	}

	public boolean promptYesNo(String str) {
		return true;
	}

	String passwd;

	public String getPassphrase() {
		return null;
	}

	public boolean promptPassphrase(String message) {
		return true;
	}

	public boolean promptPassword(String message) {
		passwd = "slipknot";
		return true;
	}

	public void showMessage(String message) {
	}

	public String[] promptKeyboardInteractive(String destination,
			String name, String instruction, String[] prompt, boolean[] echo) {
		return null;
	}
}
}